import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
//1.引入element-plus组件库
import ElementPlus, {ElMessage} from 'element-plus'
import 'element-plus/dist/index.css'
//3.引入element-plus图标库
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
//5.1修改elementPlus默认中文
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import axios from "axios";
//9.1定义常量来保存后端服务器根路径
const BASE_URL = 'http://localhost:8081';
//9.2将后端服务器根路径保存到内置全局对象window的BASE_URL属性中，效果:任意script标签中都可以使用此变量
window.BASE_URL=BASE_URL;
//9.3将BASE_URL保存到vue实例中,效果:任意template标签中都可以使用此变量
const app = createApp(App)
//4.遍历ElementPlusIconsVue对象中的所有图标组件并注册到app中
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}
app.config.globalProperties.BASE_URL=BASE_URL;
//2.app.use(ElementPlus) 使用Element-plus组件库
//5.2 app.use(ElementPlus,{ locale: zhCn })将El本地化为中文
app.use(ElementPlus,{ locale: zhCn }).use(store).use(router).mount('#app')

//6.解决ResizeObserver Error
const debounce = (fn, delay) => {
    let timer = null;
    return function () {
        let context = this;
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(context, args);
        }, delay);
    }
}
const _ResizeObserver = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
    constructor(callback) {
        callback = debounce(callback, 16);
        super(callback);
    }
}
window.getUser=()=>{
    return localStorage.user ? JSON.parse(localStorage.user) : null ;
}
router.beforeEach((to,from,next) =>{
    let user=localStorage.user;
    if(to.path!=='/login'&&!user)
        next({path:'/login'},ElMessage.error('请先登录!'));
    else next()
})

window.loadDictOptions=(object,dictCode)=>{
    axios.get(BASE_URL+'/v1/dictoption/select/'+dictCode)
        .then((response)=>{
            if (response.data.code==2000){
                object.value=response.data.data;
            }else {
                ElMessage.error(response.data.msg);
            }
        })
}